package net.caixiaomi.info.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.LotteryAdapter;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.CustomerModel;
import net.caixiaomi.info.model.LotteryItem;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.MatchFilterDialogFragment;
import net.caixiaomi.info.ui.dialog.TimeDialogFragment;
import net.caixiaomi.info.ui.football.detail.MatchDetailActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

import static android.R.id.list;
import static com.alibaba.fastjson.JSON.parseObject;

/**
 * 开奖
 */

public class LotteryFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, OnRefreshListener {
    public static final String TAG = "LotteryFragment";
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.time)
    TextView mTime;
    @BindView(R.id.other)
    TextView mAll;
    @BindView(list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    private String mCurrentTime = "";
    private String mLeagueId = "";
    private String mMatchFinish = "";
    private String mIsAlreadyBuyMatch = "";

    private LotteryAdapter mAdapter;
    private List<CustomerModel> mTimeList = new ArrayList<>();
    private List<MatchItem> mMatchList;

    public static LotteryFragment newInstance() {
        return new LotteryFragment();
    }

    @OnClick(R.id.btn_filter)
    void toFilter() {
        if (mMatchList != null) {
            String strData = JSON.toJSONString(mMatchList);
            MatchFilterDialogFragment dialog = new MatchFilterDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", strData);
            bundle.putInt("planFilter", 1);
            bundle.putString("isAlreadyBuyMatch", mIsAlreadyBuyMatch);
            dialog.setArguments(bundle);
            dialog.show(getFragmentManager(), MatchFilterDialogFragment.class.getName());
        }
    }

    @OnClick(R.id.btn_time)
    void toSelectTime() {
        try {
            String text = JSON.toJSONString(mTimeList);
            TimeDialogFragment dialog = new TimeDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", text);
            dialog.setArguments(bundle);
            dialog.show(getFragmentManager(), dialog.getClass().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.btn_other)
    void toAll(View view) {
        try {
            //比赛完成：1
            // 未完成,未选择这个条件的时候传空
            if (TextUtils.equals(mMatchFinish, "1")) {
                mMatchFinish = "";
                mAll.setText(R.string.C_ALL);
            } else {
                mAll.setText(R.string.C_HAS_FINISHED);
                mMatchFinish = "1";
            }
            loadData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected int fragmentLayout() {
        return R.layout.frag_lottery;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        mLoading = new DefLoading(getActivity());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.app_name)).append(" · ").append(getString(R.string.bottom_lottery));
        mTitle.setText(stringBuilder.toString());
        mRefresh.setOnRefreshListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new LotteryAdapter(null);
        mAdapter.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);
        createTimeList();
        loadData();
        filterConditions();
        mTime.setText(mCurrentTime);
    }


    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_TIME:
                    mLoading.show();
                    mLeagueId = "";
                    mMatchFinish = "";
                    mAll.setText(R.string.C_ALL);
                    handlePostTime(event.getMessage());
                    filterConditions();
                    loadData();
                    break;
                case EventWhat.EVENT_FOOTBALL_MATCH_FILTER:
                    mLoading.show();
                    handleMatchFilter(event.getMessage());
                    loadData();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理选择时间返回结果
     */
    private void handlePostTime(String message) {
        try {
            mTimeList = parseObject(message, new TypeToken<List<CustomerModel>>() {
            }.getType());
            for (CustomerModel item : mTimeList) {
                if (item.isSelected()) {
                    mCurrentTime = item.getName();
                    break;
                }
            }
            mTime.setText(mCurrentTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleMatchFilter(String message) {
        try {
            JSONObject object = parseObject(message);
            JSONArray dataArray = object.getJSONArray("data");
            mMatchList = parseObject(dataArray.toString(), new TypeToken<List<MatchItem>>() {
            }.getType());

            StringBuilder stringBuilder = new StringBuilder();
            for (MatchItem item : mMatchList) {
                if (item.isSelect()) {
                    stringBuilder.append(item.getLeagueId()).append(",");
                }
            }
            if (!TextUtils.isEmpty(stringBuilder)) {
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            mLeagueId = stringBuilder.toString();
            mIsAlreadyBuyMatch = object.getString("isAlreadyBuyMatch");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createTimeList() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        String curDate = dateFormat.format(currentDate);
        CustomerModel item = new CustomerModel();
        item.setName(curDate);
        item.setSelected(true);
        mCurrentTime = item.getName();
        mTimeList.add(item);
        for (int index = 1; index < 8; index++) {
            calendar.setTime(currentDate);
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - index);
            item = new CustomerModel();
            item.setName(dateFormat.format(calendar.getTime()));
            mTimeList.add(item);
        }

        Collections.reverse(mTimeList);

    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("dateStr", mCurrentTime);
        params.put("isAlreadyBuyMatch", mIsAlreadyBuyMatch);
        params.put("leagueIds", mLeagueId);
        params.put("matchFinish", mMatchFinish);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<LotteryItem>>> baseCallModelCall = requestService.queryMatchResult(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<List<LotteryItem>>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<List<LotteryItem>> data) {
                mRefresh.finishRefresh();
                mProgress.setVisibility(View.GONE);
                List<LotteryItem> lists = data.data;
                if (lists != null) {
                    LotteryItem headerItem = new LotteryItem();
                    int finishCount = 0;
                    if (!lists.isEmpty()) {
                        Iterator<LotteryItem> iterator = lists.iterator();
                        while (iterator.hasNext()) {
                            LotteryItem next = iterator.next();
                            if (TextUtils.equals(next.getMatchFinish(), "1")) {
                                finishCount++;
                            }
                        }
                    }
                    headerItem.setTotalCount(lists.size());
                    headerItem.setFinishCount(finishCount);
                    headerItem.setType(Constants.ITEM_VIEW_HEADER);
                    lists.add(0, headerItem);
                    mAdapter.setNewData(lists);
                }
                dismissLoading();
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }
        });
    }

    /**
     * 获取赛事列表
     */
    private void filterConditions() {
        JSONObject params = new JSONObject();
        params.put("dateStr", mCurrentTime);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<MatchItem>>> filterConditions = requestService.getFilterConditionsSomeDay(params);
        filterConditions.enqueue(new ResponseCallback<BaseCallModel<List<MatchItem>>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<List<MatchItem>> data) {
                mMatchList = data.data;
            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        LotteryItem lotteryItem = mAdapter.getData().get(position);
        if (TextUtils.isEmpty(lotteryItem.getMatchId()))
            return;
        Intent intent = new Intent(getActivity(), MatchDetailActivity.class);
        intent.putExtra("data", lotteryItem.getMatchId());
        startActivity(intent);
    }

    public void onRefresh() {
        loadData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        onRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onPageStart(getActivity(),"kaijaing-view");
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPageEnd(getActivity(),"kaijaing-view");
    }
}
